package com.leoman.controller.backend;

import com.leoman.common.DataTableFactory;
import com.leoman.controller.common.CommonController;
import com.leoman.entity.LetterAnnex;
import com.leoman.service.LetterAnnexService;
import com.leoman.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 物品管理
 * Created by 涂奕恒 on 2016/12/6.
 */
@Controller
@RequestMapping(value = "backend/letterAnnex")
public class LetterAnnexController extends CommonController {

    @Autowired
    private LetterAnnexService letterAnnexService;

    @RequestMapping("index")
    public String index() {
        return "backend/物品列表";
    }

    @RequestMapping("/list")
    public void list(HttpServletResponse response,
                     String name,
                     Integer type,
                     String num,
                     Integer draw,
                     Integer start,
                     Integer length) {
        if (null == start || start == 0) {
            start = 1;
        }
        int pageNum = getPageNum(start, length);
        Page<LetterAnnex> page = letterAnnexService.pageByParams(name, type, num, pageNum, length);

        Map<String, Object> result = DataTableFactory.fitting(draw, page);
        WebUtil.printJson(response, result);
    }

    @RequestMapping("add")
    public String add(ModelMap model, Integer letterAnnexId) {
        if (null != letterAnnexId) {
            LetterAnnex letterAnnex = letterAnnexService.getById(letterAnnexId);
            model.addAttribute("letterAnnex", letterAnnex);
        }

        return "backend/物品详情";
    }

    /**
     * 添加or修改物品
     */
    @RequestMapping("/save")
    @ResponseBody
    public Integer save(Integer letterAnnexId, String name, Integer type, String num, String money, String description, MultipartRequest multipartRequest) {
        try {
            return letterAnnexService.save(letterAnnexId, name, type, num, money, description, multipartRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 删除物品
     *
     * @param letterAnnexId 物品ID
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Integer delete(Integer letterAnnexId) {
        try {
            letterAnnexService.deleteById(letterAnnexId);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
